<template>
  <div class="table-detail-dialog">
    <!-- 表基本信息 -->
    <div class="detail-section">
      <h3>
        <el-icon><Coin /></el-icon>
        基本信息
      </h3>
      <div class="info-grid">
        <div class="info-item">
          <label>数据库名:</label>
          <span>{{ table.database_name }}</span>
        </div>
        <div class="info-item">
          <label>表名:</label>
          <el-tooltip :content="table.table_name" placement="top" :disabled="table.table_name.length <= 30">
            <span class="table-name-text">{{ table.table_name }}</span>
          </el-tooltip>
        </div>
        <div class="info-item">
          <label>存储引擎:</label>
          <span>{{ table.engine || '未知' }}</span>
        </div>
        <div class="info-item">
          <label>表类型:</label>
          <span>{{ table.table_type || 'BASE TABLE' }}</span>
        </div>
        <div class="info-item">
          <label>主键类型:</label>
          <span>{{ table.key_type || '未指定' }}</span>
        </div>
        <div class="info-item">
          <label>存储介质:</label>
          <el-tag :type="table.storage_medium === 'SSD' ? 'success' : 'info'" size="small">
            {{ table.storage_medium }}
          </el-tag>
        </div>
        <div class="info-item">
          <label>是否分区:</label>
          <el-tag :type="table.is_partitioned ? 'warning' : 'info'" size="small">
            {{ table.is_partitioned ? '是' : '否' }}
          </el-tag>
        </div>
        <div class="info-item" v-if="table.partition_field">
          <label>分区字段:</label>
          <span>{{ table.partition_field }}</span>
        </div>
        <div class="info-item">
          <label>字段总数:</label>
          <span>{{ table.total_columns || 0 }}</span>
        </div>
        <div class="info-item">
          <label>监控状态:</label>
          <el-switch
            v-model="table.monitor_enabled"
            @change="toggleMonitor"
            :loading="switching"
          />
        </div>
      </div>
      
      <div class="info-item full-width" v-if="table.table_comment">
        <label>表注释:</label>
        <p class="table-comment">{{ table.table_comment }}</p>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="detail-section">
      <h3>
        <el-icon><TrendCharts /></el-icon>
        统计信息
        <el-button size="small" @click="refreshStats" :loading="refreshing">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </h3>
      
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon rows">
            <el-icon><DataBoard /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatNumber(table.total_rows) }}</div>
            <div class="stat-label">总行数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon data">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatBytes(table.data_length) }}</div>
            <div class="stat-label">数据大小</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon previous">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" :class="getIncrementClass(table.previous_increment_rows)">
              {{ formatIncrement(table.previous_increment_rows) }}
            </div>
            <div class="stat-label">上次增量</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon current">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" :class="getIncrementClass(table.current_increment_rows)">
              {{ formatIncrement(table.current_increment_rows) }}
            </div>
            <div class="stat-label">当前增量</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon total">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" :class="getIncrementClass(table.total_increment_rows)">
              {{ formatIncrement(table.total_increment_rows) }}
            </div>
            <div class="stat-label">总增量(今日)</div>
          </div>
        </div>
      </div>
      
      <div class="stats-actions">
        <el-button @click="viewStatsHistory">
          <el-icon><TrendCharts /></el-icon>
          查看历史趋势
        </el-button>
      </div>
    </div>

    <!-- 字段信息 -->
    <div class="detail-section">
      <h3>
        <el-icon><List /></el-icon>
        字段信息 ({{ columns.length }})
        <el-button size="small" @click="loadColumns" :loading="loadingColumns">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </h3>
      
      <div class="columns-table">
        <el-table
          v-loading="loadingColumns"
          :data="columns"
          height="300"
          size="small"
        >
          <el-table-column prop="ordinal_position" label="序号" width="60" />
          <el-table-column prop="column_name" label="字段名" min-width="120">
            <template #default="{ row }">
              <span class="column-name">{{ row.column_name }}</span>
              <el-tag v-if="row.column_key === 'PRI'" size="small" type="danger">主键</el-tag>
              <el-tag v-else-if="row.column_key === 'UNI'" size="small" type="warning">唯一</el-tag>
              <el-tag v-else-if="row.column_key === 'MUL'" size="small" type="info">索引</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="column_type" label="类型" width="150">
            <template #default="{ row }">
              <code class="column-type">{{ row.column_type }}</code>
            </template>
          </el-table-column>
          <el-table-column prop="is_nullable" label="可空" width="60">
            <template #default="{ row }">
              <el-tag :type="row.is_nullable === 'YES' ? 'success' : 'danger'" size="small">
                {{ row.is_nullable === 'YES' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="column_default" label="默认值" width="100" show-overflow-tooltip>
            <template #default="{ row }">
              <code v-if="row.column_default" class="default-value">{{ row.column_default }}</code>
              <span v-else class="no-default">NULL</span>
            </template>
          </el-table-column>
          <el-table-column prop="column_comment" label="注释" min-width="150" show-overflow-tooltip />
          <el-table-column prop="extra" label="额外" width="100" show-overflow-tooltip />
        </el-table>
      </div>
    </div>

    <!-- 最近统计历史 -->
    <div class="detail-section" v-if="recentStats.length > 0">
      <h3>
        <el-icon><DataLine /></el-icon>
        最近统计记录 ({{ recentStats.length }})
      </h3>
      
      <div class="stats-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="stat in recentStats"
            :key="stat.id"
            :timestamp="formatTime(stat.stat_time)"
            placement="top"
          >
            <div class="timeline-content">
              <div class="timeline-stats">
                <span class="stat-item">
                  <strong>{{ formatNumber(stat.total_rows) }}</strong> 行
                </span>
                <span class="stat-item">
                  <strong>{{ formatBytes(stat.data_length) }}</strong>
                </span>
                <span class="stat-item" v-if="stat.increment_rows !== 0">
                  增量: <strong :class="getIncrementClass(stat.increment_rows)">
                    {{ formatIncrement(stat.increment_rows) }}
                  </strong>
                </span>
              </div>
              <div class="timeline-meta">
                <el-tag size="small" :type="getStatTypeTag(stat.stat_type)">
                  {{ getStatTypeLabel(stat.stat_type) }}
                </el-tag>
                <el-tag size="small" type="info">
                  {{ stat.collection_method }}
                </el-tag>
                <span class="duration">{{ stat.collection_duration_ms }}ms</span>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="dialog-actions">
      <el-button @click="$emit('close')">关闭</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Coin, TrendCharts, Refresh, List, DataBoard, Files, Clock, Calendar,
  DataLine, Download
} from '@element-plus/icons-vue'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { useRouter } from 'vue-router'
import api from '@/utils/api'
import { logger } from '@/utils/logger'

const props = defineProps({
  table: {
    type: Object,
    required: true
  },
  configId: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['close'])
const router = useRouter()

// 响应式数据
const switching = ref(false)
const refreshing = ref(false)
const loadingColumns = ref(false)
const columns = ref([])
const recentStats = ref([])
const isInitializing = ref(true)

// 格式化函数 - 使用中文单位（支持负数）
const formatNumber = (num) => {
  if (!num) return '0'
  
  // 处理负数：保留符号，用绝对值计算单位
  const isNegative = num < 0
  const absNum = Math.abs(num)
  const sign = isNegative ? '-' : ''
  
  if (absNum >= 1e8) {
    const value = absNum / 1e8
    return sign + (value >= 10 ? Math.round(value) + '亿' : value.toFixed(1) + '亿')
  }
  if (absNum >= 1e4) {
    const value = absNum / 1e4
    return sign + (value >= 10 ? Math.round(value) + '万' : value.toFixed(1) + '万')
  }
  return num.toLocaleString('zh-CN')
}

const formatBytes = (bytes) => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]
}

const formatIncrement = (increment) => {
  if (!increment) return '0'
  const sign = increment > 0 ? '+' : ''
  return sign + formatNumber(increment)
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    return formatDistanceToNow(new Date(timeStr), { 
      addSuffix: true, 
      locale: zhCN 
    })
  } catch {
    return timeStr
  }
}

const getIncrementClass = (increment) => {
  if (increment > 0) return 'positive'
  if (increment < 0) return 'negative'
  return 'zero'
}

const getStatTypeTag = (type) => {
  const types = {
    'hourly': 'primary',
    'daily': 'success',
    'manual': 'warning'
  }
  return types[type] || 'info'
}

const getStatTypeLabel = (type) => {
  const labels = {
    'hourly': '小时统计',
    'daily': '日统计',
    'manual': '手动统计'
  }
  return labels[type] || type
}

// API调用
const loadTableDetail = async () => {
  try {
    const response = await api.get(`/starrocks-tables/tables/${props.table.id}`)
    if (response.data.success) {
      const data = response.data.data
      columns.value = data.columns || []
      recentStats.value = data.recent_stats || []
    }
  } catch (error) {
    logger.error('加载表详情失败:', error)
    ElMessage.error('加载表详情失败')
  }
}

const loadColumns = async () => {
  loadingColumns.value = true
  try {
    // 只更新当前表的结构和字段（优化：只传当前表ID）
    logger.info(`刷新表 ${props.table.id} 的字段信息...`)
    const response = await api.post('/starrocks-tables/schema/batch-update', {
      config_id: props.configId,
      database: '',  // 不限制数据库
      selected_table_ids: [props.table.id]  // 只更新当前表
    })
    
    if (response.data.success) {
      // 重新加载详情
      await loadTableDetail()
      ElMessage.success(`字段刷新成功：${response.data.data.success_tables}个表`)
    } else {
      ElMessage.error('字段刷新失败')
    }
  } catch (error) {
    logger.error('刷新字段失败:', error)
    ElMessage.error('刷新字段失败: ' + (error.response?.data?.error || error.message))
  } finally {
    loadingColumns.value = false
  }
}

const toggleMonitor = async () => {
  // 防止页面初始化时触发
  if (isInitializing.value) {
    logger.info('详情对话框初始化中，跳过监控状态切换...')
    return
  }
  
  switching.value = true
  try {
    const response = await api.put(`/starrocks-tables/tables/${props.table.id}/monitor`, {
      monitor_enabled: props.table.monitor_enabled
    })
    
    if (response.data.success) {
      ElMessage.success(`${props.table.monitor_enabled ? '启用' : '禁用'}监控成功`)
    }
  } catch (error) {
    logger.error('切换监控状态失败:', error)
    ElMessage.error('切换监控状态失败')
    // 回滚状态
    props.table.monitor_enabled = !props.table.monitor_enabled
  } finally {
    switching.value = false
  }
}

const refreshStats = async () => {
  refreshing.value = true
  try {
    // 执行 COUNT 统计 - 超时10分钟
    const response = await api.post(`/starrocks-tables/tables/${props.table.id}/count`, {
      config_id: props.configId
    }, {
      timeout: 600000  // 10分钟
    })
    if (response.data.success || response.data) {
      const result = response.data.data || response.data
      
      // 更新表统计数据（三增量设计）
      props.table.total_rows = result.total_rows
      if (result.data_length && result.data_length > 0) {
        props.table.data_length = result.data_length
      }
      props.table.last_stat_time = result.stat_time
      
      // 更新三增量字段
      props.table.previous_increment_rows = result.previous_increment || 0
      props.table.current_increment_rows = result.current_increment || 0
      props.table.total_increment_rows = result.total_increment || 0
      
      // 重新加载详情
      await loadTableDetail()
      
      ElMessage.success(`统计完成｜上次${formatIncrement(result.previous_increment)}，当前${formatIncrement(result.current_increment)}，总计${formatIncrement(result.total_increment)}`)
    }
  } catch (error) {
    logger.error('刷新统计失败:', error)
    ElMessage.error('刷新统计失败')
  } finally {
    refreshing.value = false
  }
}

const viewStatsHistory = () => {
  router.push(`/tools/starrocks-tables/${props.table.id}/stats`)
}

// 生命周期
onMounted(async () => {
  try {
    await loadTableDetail()
  } finally {
    // 对话框初始化完成，允许监控状态切换
    setTimeout(() => {
      isInitializing.value = false
      logger.info('表详情对话框初始化完成，监控状态切换已启用')
    }, 500) // 延迟500ms确保数据绑定完成
  }
})
</script>

<style scoped>
.table-detail-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 32px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.detail-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
  flex-direction: column;
  align-items: flex-start;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  flex-shrink: 0;
}

.info-item span {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.table-name-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
}

.table-comment {
  margin: 8px 0 0 0;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  color: #2c3e50;
  font-style: italic;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.stat-icon.rows { background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%); }
.stat-icon.data { background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%); }
.stat-icon.previous { background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%); }
.stat-icon.current { background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%); }
.stat-icon.total { background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%); }

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-number.positive { color: #67c23a; }
.stat-number.negative { color: #f56c6c; }
.stat-number.zero { color: #909399; }

.stat-label {
  color: #909399;
  font-size: 12px;
}

.stats-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.columns-table {
  background: white;
  border-radius: 4px;
  overflow: hidden;
}

.column-name {
  font-weight: 500;
  margin-right: 8px;
}

.column-type {
  background: #f1f2f6;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  color: #2c3e50;
}

.default-value {
  background: #e8f4fd;
  color: #1890ff;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 12px;
}

.no-default {
  color: #c0c4cc;
  font-style: italic;
  font-size: 12px;
}

.stats-timeline {
  background: white;
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.timeline-content {
  padding: 8px 0;
}

.timeline-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.stat-item {
  font-size: 14px;
  color: #2c3e50;
}

.timeline-meta {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.duration {
  color: #909399;
  font-size: 12px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin: 16px -24px -24px -24px;
  padding: 16px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 12px 12px;
}

.positive { color: #67c23a; }
.negative { color: #f56c6c; }
.zero { color: #909399; }
</style>
